<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto">
            <el-card shadow="hover" style="display: flex; flex-direction: column; flex: 1; height: inherit">
				<section style="flex: 1; height: inherit;overflow-y: auto;">
                    <el-form ref="ruleFormRef" :model="state.upgradeData" :rules="rules" label-width="220px">
                        <section v-for="(itemX,indexX) in state.selectGoods" :key="indexX">
                            <el-form-item label="商品信息：">
                                <el-image class="mr20" style="width:64px; height: 64px;border-radius: 5px;" :src="itemX.imgUrl" fit="cover" />
                                <section style="display: flex; flex-direction: column;">
                                    <span>{{itemX.spuName}}</span>
                                    <span>{{itemX.priceRange}} 元</span>
                                </section>
                            </el-form-item>
                            <el-form-item label="代理价格设置：">
                                <el-table :data="itemX.skuList" border row-key="skuId">
                                    <el-table-column v-for="(item, index) of itemX.specList"  :label="item.name" :key="index" width="100">
                                        <template #default="scope">
                                            <span>{{ scope.row.skuSpecEntry[index].name }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-for="(item, index) of state.agentLevelList" :key="index" :label="item.agentName" show-overflow-tooltip>
                                        <template v-slot="scope">
                                            <el-form-item>
                                                <el-input placeholder="请输入" type="number" v-model.number="scope.row.agentPriceValue[index].agentCustomValue">
                                                    <template #prepend>
                                                        <el-select placeholder="请选择" class="width140" v-model="scope.row.agentPriceValue[index].agentPriceType">
                                                            <el-option label="折扣比例" :value= 1 />
                                                            <el-option label="固定金额" :value= 2 />
                                                        </el-select>
                                                    </template>
                                                    <template #append>
                                                        <span> {{ scope.row.agentPriceValue[index].agentPriceType == 1 ? '%' : '元' }}</span>
                                                    </template>
                                                </el-input>
                                            </el-form-item>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>
                            <el-form-item label="首次进货自定义价格：">
                                <section style="width:100%">
                                    <el-switch v-model="itemX.agentFirstStockDiscountType" :active-value=1 :inactive-value=0 />
                                    <el-col :span="24" v-if="itemX.agentFirstStockDiscountType == 1">
                                        <el-table :data="itemX.skuList" border row-key="skuId">
                                            <el-table-column v-for="(item, index) of itemX.specList"
                                                :label="item.name" :key="index" width="100">
                                                <template #default="scope">
                                                   <span>{{ scope.row.skuSpecEntry[index].name }}</span>
                                                </template>
                                            </el-table-column>
                                            <el-table-column v-for="(item, index) of state.agentLevelList" :key="index" :label="item.agentName" show-overflow-tooltip>
                                                <template v-slot="scope">
                                                    <el-form-item>
                                                        <el-input placeholder="请输入" v-model.number="scope.row.agentFirstStockDiscountValue[index].agentCustomValue">
                                                            <template #prepend>
                                                                <el-select placeholder="请选择" class="width140" v-model="scope.row.agentFirstStockDiscountValue[index].agentPriceType">
                                                                    <el-option label="折扣比例" :value= 1 />
                                                                    <el-option label="固定金额" :value= 2 />
                                                                </el-select>
                                                            </template>
                                                            <template #append>
                                                                <span> {{ scope.row.agentFirstStockDiscountValue[index].agentPriceType == 1 ? '%' : '元' }}</span>
                                                            </template>
                                                        </el-input>
                                                    </el-form-item>
                                                </template>
                                            </el-table-column>
                                        </el-table>   
                                    </el-col>
                                </section>
                            </el-form-item>
                            <el-form-item label="升级补货自定义价格：">
                                <section style="width:100%">
                                    <el-switch v-model="itemX.agentReplenishmentType" :active-value=1 :inactive-value=0 />
                                    <el-col :span="24" v-if="itemX.agentReplenishmentType == 1">
                                        <el-table :data="itemX.skuList" border row-key="skuId">
                                            <el-table-column v-for="(item, index) of itemX.specList"
                                                :label="item.name" :key="index" width="100">
                                                <template #default="scope">
                                                    <span>{{ scope.row.skuSpecEntry[index].name }}</span>
                                                </template>
                                            </el-table-column>
                                            <el-table-column v-for="(item, index) of state.agentLevelList" :key="index" :label="item.agentName" show-overflow-tooltip>
                                                <template v-slot="scope">
                                                    <el-form-item>
                                                        <el-input placeholder="请输入" v-model.number="scope.row.agentReplenishmentValue[index].agentCustomValue">
                                                            <template #prepend>
                                                                <el-select placeholder="请选择" class="width140" v-model="scope.row.agentReplenishmentValue[index].agentPriceType">
                                                                    <el-option label="折扣比例" :value= 1 />
                                                                    <el-option label="固定金额" :value= 2 />
                                                                </el-select>
                                                            </template>
                                                            <template #append>
                                                                <span> {{ scope.row.agentReplenishmentValue[index].agentPriceType == 1 ? '%' : '元' }}</span>
                                                            </template>
                                                        </el-input>
                                                    </el-form-item>
                                                </template>
                                            </el-table-column>
                                        </el-table> 
                                    </el-col>
                                </section>
                            </el-form-item>
                            <el-divider />
                        </section>
                    </el-form>
                </section>
                <section style="text-align: center; margin:10px 0;">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                </section>
            </el-card>
        </div>
	</div>
</template>
<script setup lang="ts" name="funWangEditor">
import { reactive, onMounted, ref, defineAsyncComponent } from 'vue';
import { configData } from '/@/api/common';
import { agentList, goodsPriceSave, getUpgrade  } from "/@/api/agent";
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { number } from 'echarts';
const route = useRoute();
const AddConditions = defineAsyncComponent(() => import('/@/views/agent/upgrade/components/addConditions.vue'))
const useTypeDialog = defineAsyncComponent(() => import('/@/components/createGoods/useTypeDialog.vue'))
// 引入组件
const goodSelectDialog = defineAsyncComponent(() => import('/@/components/dialog/goodSelect.vue'));
// 定义变量内容
const goodSelectDialogRef = ref();
const useTypeDialogRef = ref()
const emit = defineEmits(['stepChange'])
const ruleFormRef = ref<FormInstance>()
const AddConditionsRef = ref()
const state = reactive({
    param:{
        agentFirstStockDiscountType:0,
        agentReplenishmentType:0,
    },
    selectGoods: [] as Array<any>,
    index2: null,
    index3: null,
    agentLevelList: [] as Array<any>,
    upgradeData:{
        upgradeIsInitiative: 0,   //  否主动升级0否 1是
        upgradeIsCondition: 0,  //0 无条件 1需满足规定条件
        upgradeMode: 0, // 0 自动升级 1 手动升级
        auditMode: 0, //审核方式  0 自动审核  1手动审核
        auditorType: [], // 审核人类型
        levelIds:[],
        mechanisms: [] as Array<any>, //代理升级机制
    },
    tableData:[{}]
})


const rules = reactive<FormRules<any>>({
	couponBaseType: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
	name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
	money: [{ required: true, message: '请选择优惠券面值', trigger: 'blur' }],
	type: [{ required: true, message: '请选择优惠券领取方式', trigger: 'change' }],
	useType: [{ required: true, message: '请选择优惠券使用类型', trigger: 'change' }],
})

// 删除机制
const delJIZHI = (val:number) => {
    state.upgradeData.mechanisms.splice(val,1)
    state.upgradeData.levelIds = state.upgradeData.mechanisms.map(obj => obj.agentLevelId);
}

// 新增机制
const addJIZHI = (val: number) => {
	state.upgradeData.mechanisms[val].mechanisms.push({ conditions:[],selectId:null})
}

// 使用类型选择弹窗
const addGoodsFile = (index:any,indexX:any,indexY:any) => {
    state.index1 = index;
    state.index2 = indexX;
    state.index3 = indexY;
    goodSelectDialogRef.value.openDialog();
}

// 选中关联商品
const goodsSubmitFun = (list: any) =>{
    if(list.length > 0){
        state.upgradeData.mechanisms[state.index1].mechanisms[state.index2].conditions[state.index3].skuName = list[0].spuName;
        state.upgradeData.mechanisms[state.index1].mechanisms[state.index2].conditions[state.index3].skuId = list[0].skuId
    }
}

// 获取商品品牌列表
const getAgentList = async () => {
	const { results } = await agentList();
	state.agentLevelList = results;
    state.selectGoods.map((item:any) => {
        item.skuList.map((itemX:any) => {
            let listArr = [] as Array <any>;
            state.agentLevelList.map((itemXX:any) => {
                listArr.push({
                    agentPriceType: 1,
                    agentLevelId: itemXX.agentLevelId,
                    agentCustomValue: null
                })
            })
            itemX.agentPriceValue = JSON.parse(JSON.stringify(listArr));
            itemX.agentFirstStockDiscountValue = JSON.parse(JSON.stringify(listArr));
            itemX.agentReplenishmentValue = JSON.parse(JSON.stringify(listArr));
        })
    })
}


// 页面加载时
onMounted(()  => {
    getAgentList()
    state.selectGoods = JSON.parse(localStorage.getItem('selectGoods'));
});

 
// 添加条件
const addCondition = (index:number,indexX:number,id:number) => {
    AddConditionsRef.value.openDialog(index,indexX,id);
}

// 选择条件返回值
const selectFun = (index:any,indexX:any,id:any,idList:any) => {
    console.log(idList);
    idList.map((x:any,i:number)=>{
        state.upgradeData.mechanisms[index].mechanisms[indexX].conditions.push({
            conditionType:x
        })
    })
    // 非重复条件
    if(id != null){
        state.upgradeData.mechanisms[index].mechanisms[indexX].uniqueConditions = [{
            conditionType:id
        }]
    }
    
}



// 删除机制
const delItem = (index:any,indexX:any,) => {
    state.upgradeData.mechanisms[index].mechanisms.splice(indexX,1)
}


const agentLevelFun = () => {
    //  根据当前付费会员等级生成会员积分数据
    let dataList = []as Array<any>;
    state.upgradeData.levelIds.map((item:any) => {
        let selectData = state.agentLevelList.find(obj => obj.agentLevelId == item);
        console.log(JSON.stringify(selectData))
        let dataItem = {
            agentLevelId: selectData.agentLevelId, // 代理等级ID
            agentLevelName: selectData.agentName,  // 代理等级名称
            agentLevel: selectData.agentLevel,  // 权重ID
            mechanisms: [{ conditions:[],uniqueConditions:[]}], //代理升级条件列表
        };
        dataList.push(dataItem);
    })
    state.upgradeData.mechanisms = dataList;
}


// 代理升级信息提交
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate( async (valid, fields) => {
		if (valid) {
			// let params = {
            //     base:{
            //         upgradeIsInitiative: state.upgradeData.upgradeIsInitiative, // 代理是否主动升级
            //         upgradeIsCondition: state.upgradeData.upgradeIsCondition,  // 代理升级条件
            //         upgradeMode: state.upgradeData.upgradeMode,// 代理发起条件
            //         auditMode: state.upgradeData.auditMode,// 代理条件审核设置
            //         auditorType: state.upgradeData.auditorType, // 审核人类型设置
            //     },
            //     mechanisms: state.upgradeData.mechanisms,
            // }
            const { method } = await goodsPriceSave(state.selectGoods);
            if(method == 'success'){
                ElMessage.success('提交成功');
                // window.location.reload();
            }
            console.log(results)
		} else {
			console.log('error submit!', fields)
		}
	})
}

</script>

<style lang="scss" scoped>
:deep(.el-card__body) {
	display: flex;
	flex-direction: column;
	flex: 1;
	height: inherit;
}
.el-form{
    flex:1;
    overflow-y: auto;
    position: relative;
}
.form-ele-size {
    width: 260px;
}

.line-title {
    font-size: 18px;
    padding: 8px 12px;
    background-color: #eceef0;
    border-radius: 6px;
    margin-bottom: 15px;
}

.selector-img {
    // width: 64px;
    // height: 64px;
    // border: 1px solid #ededed;
    // border-radius: 5px;
    // position: relative;
    // display: flex;
    // justify-content: center;
    // align-items: center;
    // &:hover {
    //     background-color: #f5f5f5;
    //     border: 1px solid #e4e3e3;
    // }
}
.typeBox{
    height: 65px;
    margin-right: 15px;
    border: 1px solid var(--el-border-color-light, #ebeef5);
    line-height: 24px;
    box-sizing: border-box;
    cursor: pointer;
    span:first-child{
        font-weight: 600;
    }
    span:last-child{
        font-weight: 500;
        color: var(--el-color-info-light-3);
    }
}
.typeBoxSelected {
    border: 1px solid var(--el-color-primary);
    position: relative;
    .virtual_san{
        position: absolute;
        bottom: 0;
        right: 0;
        width: 0;
        height: 0;
        border-bottom: 26px solid var(--el-color-primary);
        border-left: 26px solid transparent;
    }
    .virtual_dui{
        position: absolute;
        bottom: -2px;
        right: 2px;
        color: #fff;
        font-family: system-ui;
    }
}

:deep(.el-form .el-form-item:last-of-type){
    margin-bottom: 0px !important;
}
</style>
